/* Copyright (C) 2010 Moritz Bitsch
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 *
 * Author:
 *      Moritz Bitsch <moritzbitsch@googlemail.com>
 */

namespace Webappi {
	public class Cookie {
		public string name {get; set; default="";}
		public string val {get; set; default="";}

		public string path {get; set; default="";}
		public string domain {get; set; default="";}
		public string max_age {get; set; default="";}
		public bool secure {get; set; default=false;}
		public bool delete {get; set; default=false;}

		public string[] to_cookie() {
			var result = new string[2];
			result[0] = "Set-cookie";


			var builder = new StringBuilder();

			if (this.delete){
				this.max_age = "0";
			}

			builder.append("%s=%s".printf(this.name, this.val));


			if (this.path != "") {
				builder.append("; Path=%s".printf(this.path));
			}
			if (this.domain != "") {
				builder.append("; Domain=%s".printf(this.domain));
			}
			if (this.max_age != "") {
				builder.append("; Max-age=%s".printf(this.max_age));
			}
			if (this.secure) {
				builder.append("; Secure");
			}

			builder.append("; Version=1");

			result[1] = builder.str;

			return result;
		}

		public static HashTable<string,Cookie> get_cookies(scgi.Request req) {
			var result = new HashTable<string,Cookie>.full(str_hash,str_equal, g_free, Cookie.unref);

			var cookies = req.params.lookup("HTTP_COOKIE");

			if (cookies == null) {
				return result;
			}

			foreach (string pair in cookies.split("; ")) {
				var kv = pair.split("=");
				if (kv.length == 2) {
					var tmpCookie = new Cookie();
					tmpCookie.name = Uri.unescape_string(kv[0]);
					tmpCookie.val = Uri.unescape_string(kv[1]);
					result.insert(kv[0], tmpCookie);
				}
			}
			return result;
		}

		public static extern new void unref(void* self);
	}
}
